import request from "@/utils/request.ts";
import * as qiniu from 'qiniu-js'
import { UploadProgress } from "qiniu-js/esm/upload";

// 获取上传token
export const getUploadToken = (bucket?: string, key?: string): Promise<IResponse<{ token: string }>> => {
  return request.post<IResponse<{
    token: string
  }>>('api/upload/upload_token', { bucket: bucket || import.meta.env.VITE_QINIU_BUCKET, key })
}

// 上传自定义模板内容
export const uploadCustomTemplate = async (content: string, onProgress?: (p: UploadProgress) => void) => {
  const file = new Blob([ content ], { type: "text/xml" }) as File
  const tokenRes = await getUploadToken()
  if (!tokenRes?.data?.token) throw new Error(tokenRes.message || '无法获取上传token')
  const ob = qiniu.upload(file, 'templates/' + new Date().getTime() + '.xml', tokenRes.data.token)
  return await new Promise<string>((resolve, reject) => {
    ob.subscribe({
      next: onProgress,
      error: reject,
      complete: res => {
        if (res.key) resolve(import.meta.env.VITE_QINIU_DOMAIN + res.key)
        else reject(new Error('模板上传失败'))
      }
    })
  })
}